/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { ref, SetupContext } from 'vue';
import { TooltipProps } from '../tooltip.props';
import { UseRelative } from './types';

export function useRelative(props: TooltipProps, context: SetupContext): UseRelative {
    const horizontalRelativeElement = ref(props.horizontalRelative);

    const verticalRelativeElement = ref(props.verticalRelative);

    /**
     * 获取纠正元素
     */
    function getRelativeElement(relativeElement: any) {
        if (typeof relativeElement == 'string') {
            return document.querySelector(relativeElement as string);
        }
        return relativeElement;
    }

    /**
     * 确认参照的边界
     */
    function getRelativeElementBound(): DOMRect {
        let right = document.documentElement.clientWidth;
        let bottom = document.documentElement.clientHeight;
        let top = 0;
        let left = 0;
        let x = 0;
        let y = 0;
        let height = bottom - top;
        let width = right - left;
        // 横向参照
        if (horizontalRelativeElement.value) {
            const rectifyReferenceHEl = getRelativeElement(horizontalRelativeElement.value);
            ({ left, right, x, width } = rectifyReferenceHEl.getBoundingClientRect());
        }
        // 纵向参照
        if (verticalRelativeElement.value) {
            const rectifyReferenceVEl = getRelativeElement(verticalRelativeElement.value);
            ({ bottom, top, y, height } = rectifyReferenceVEl.getBoundingClientRect());
        }
        return { top, left, right, bottom, height, width, x, y } as DOMRect;
    }

    return { getRelativeElementBound };
}
